<?php
namespace Shopmodule\Controller;
use Think\Controller;
class IndexController extends ExtendController {
	public function normallot(){
		// 普通大转盘等抽奖
	$usernick = I("get.usernick");
	$ts = I("get.ts");
	$sign = I("get.sign");
	$top_sign = I("get.top_sign");
	$oid = I("get.oid");
	$rd = I("get.rd");
		if(md5($this->sid."|".$oid."|".$usernick."|".$top_sign."|".C("FRONT_SECRET").$ts)==$sign){
			if($oid){
				$cacheService->set($usernick."oid",$oid);
			}
			$usernick = urldecode_utf8($usernick);
			$User = M("User");
			$this->UserUZID = $User->where("`usernick`='".$usernick."'")->getField("id");
			if(!$this->UserUZID){
				$data = array();
				$data["usernick"]=$usernick;
				$data["jointime"]=date("Y-m-d H:i:s",time());
				$this->UserUZID = $User->add($data);
			}
			$ShopUser = M("ShopUsers");
			$this->UserSPID = $ShopUser->where("`userid`=".$this->UserUZID." AND `sid`=".$this->sid)->getField("id");
			if(!$this->UserSPID){
				$data = array();
				$data["sid"]=$this->sid;
				$data["userid"]=$this->UserUZID;
				$data["addtime"]=date("Y-m-d H:i:s",time());
				$this->UserSPID = $ShopUser->add($data);
			}
			$L = D("Lottery");
			$L->sid=$this->sid;
			$L->UserUZID=$this->UserUZID;
			$L->UserSPID=$this->UserSPID;
			$L->usernick=$usernick;
			$L->oid=$oid;
			$L->readoid=$rd;
			$reda = $L->ShopLott();
			if(!$reda){
			$data["status"]=false;
			$data["giftname"]="没有返回！！！";
			}else{
				$data=$reda;
				if($reda["gid"]>0 && $reda["type"]==1){
					// 更新备注
					$coid = $cacheService->get($usernick."oid");
					if($coid){
						Vendor('taobaosdk.top.request.TradeGetRequest');
						Vendor('taobaosdk.top.request.TradeMemoUpdateRequest');
						$sessionKey = $cacheService->get($this->sid."key");
						if(!$sessionKey){
							$SHOP = M("ShopCfg");
							$sessionKey = $SHOP->where("`sid`=".$this->sid)->limit(1)->getField("sessionkey");
							$cacheService->set($this->sid."key",$sessionKey);
						}
						$req = new \TradeGetRequest;
						$req->setFields("seller_memo");
						$req->setTid($coid);
						$resp = $this->c->execute($req, $sessionKey);
						$memo = $resp->trade->seller_memo;
						
						$req = new \TradeMemoUpdateRequest;
						$req->setTid($coid);
						$req->setMemo(date("Ymd H:i:s")."中奖，奖品：（".$data["giftname"]."）-订单抽大奖备注\n".$memo);
						$req->setFlag("1");
						$req->setReset("false");
						$resp = $this->c->execute($req, $sessionKey);
						
						$data["resp"]=$resp;
					}
				}
			}
		}else{
			$data["status"]=false;
			$data["giftname"]="sign err".$this->sid.$sign."|".(md5($this->sid."|".$usernick."|".$top_sign."|".C("FRONT_SECRET").$ts));
		}
		$this->ajaxReturn($data);
		
	}
	
	public function dolotts(){
		// 躲星星等游戏结束后抽奖
		$usernick = I("get.usernick");
		$lastscoreid = I("get.lastscoreid");
		$lastrange = I("get.lastrange");
		$lotts = I("get.lotts");
		$ts = I("get.ts");
		$sign = I("get.sign");
		$oid = I("get.oid");
		//$cacheService = D("Home/Catche");
		if(md5($this->sid."|".$oid."|".$usernick."|".$lastscoreid."|".$lastrange."|".$lotts.C("FRONT_SECRET").$ts)==$sign){
			$usernick = urldecode_utf8($usernick);
			$User = M("User");
			$this->UserUZID = $User->where("`usernick`='".$usernick."'")->getField("id");
			if(!$this->UserUZID){
				$data = array();
				$data["usernick"]=$usernick;
				$data["jointime"]=date("Y-m-d H:i:s",time());
				$this->UserUZID = $User->add($data);
			}
			$ShopUser = M("ShopUsers");
			$this->UserSPID = $ShopUser->where("`userid`=".$this->UserUZID." AND `sid`=".$this->sid)->getField("id");
			if(!$this->UserSPID){
				$data = array();
				$data["sid"]=$this->sid;
				$data["userid"]=$this->UserUZID;
				$data["addtime"]=date("Y-m-d H:i:s",time());
				$this->UserSPID = $ShopUser->add($data);
			}
			if($cacheService->get($this->safe."score_id")){
				$L = D("Lottery");
				$L->sid=$this->sid;
				$L->UserUZID=$this->UserUZID;
				$L->UserSPID=$this->UserSPID;
				$L->score_id=$cacheService->get($this->safe."score_id");
				$reda = $L->ShopLott();
				$data=$reda;
			}else{
				$data["status"]=false;
				$data["giftname"]="你耽搁太久时间了哦，好成绩已经消失了。请再来一遍吧！";
			}
		}else{
		$data["status"]=false;
		$data["giftname"]="sign err";
		}
		$this->ajaxReturn($data);
	}
	public function tsm_st(){
		//$cacheService = D("Home/Catche");
		if(!$this->top_sign){
			$data["status"]=false;
		}else{
			$cacheService->set($this->safe."game_start_time",time(),60);
			$data["status"]=true;
		}
		$this->ajaxReturn($data);
	}
	public function tsm_ed(){
		//$cacheService = D("Home/Catche");
		$url_score = I("get.score");
		$url_level = I("get.level");
		$sign = I("get.sign");
		$ts = I("get.ts");
		if(md5($this->sid."|".$url_score."|".$url_level."8o79a".$ts)==$sign){
			$score = (int)(time()-$cacheService->get($this->safe."game_start_time"));
			$end_time = time();
			$start_time = $cacheService->get($this->safe."game_start_time");
			
			$CFG = M("ShopCfg");
			$cfg = current($CFG->where("`sid`=".$this->sid)->getField("id,curtool,range_time,game_lv1_times,game_lv2_times,game_lv3_times,game_def_times"));
			$curtool = $cfg["curtool"];
			$range_time = $cfg["range_time"];
			$range_lotts[]=$cfg["game_lv1_times"];
			$range_lotts[]=$cfg["game_lv2_times"];
			$range_lotts[]=$cfg["game_lv3_times"];
			$range_lotts[]=$cfg["game_def_times"];
			
			$Score = M("GameScore");
			// $save["mixednick"]=$this->top_sign;
			$save["top_sign"]=$this->top_sign;
			$save["top_parameters"]=$this->top_parameters;
			$save["score"]=$url_score;
			$save["start_time"]=date("Y-m-d H:i:s",$start_time);
			$save["end_time"]=date("Y-m-d H:i:s",$end_time);
			$save["level"]=$url_level;
			$save["sid"]=$this->sid;
			$save["status"]=1;
			$save["game_id"]=1;
			$save["game_name"]=$curtool;
			
			$RANG = D("RangeTime");
			$save["time_round"]=$RANG->getrangetime($range_time,$start_time);
			$save["sys_score"]=$score;
			$score_id = $Score->add($save);
			
			$paihang = $Score->where("`time_round`='".$RANG->getrangetime($range_time,time())."'")
							 ->order("`score` DESC,`id` DESC")
							 ->group("`score`,`mixednick`")
							 ->getField("id,score,mixednick");
			// $data["sql"]=$Score->_sql();
			$i=1;
			foreach($paihang as $k=>$sc){
				if($sc["score"]==$url_score){
				 // && $sc["mixednick"]==$this->MixedNick  //未提交时，没有昵称限制
					break;
				}
				$i++;
			}
			if($score_id){
				$sa["id"]=$data["score_id"]=$score_id;
				$sa["range_level"]=$data["range"]=$i;
				if($i<=3){
					$sa["lotts"]=$data["lotts"]=$range_lotts[$i-1];
				}else{
					$sa["lotts"]=$data["lotts"]=$range_lotts[3];
				}
				$Score->save($sa);
				$data["status"]=true;
				$cacheService->set($this->safe."score_id",$score_id,3600);
			}else{
				$data["status"]=false;
			}
		}else{
			$data["status"]=false;
		}
		$this->ajaxReturn($data);
	}

	public function tsm(){
		//$cacheService = D("Home/Catche");
		$ping = I("get.ping");
		$lst_ping = $cacheService->get($this->safe."ping");
		$ping_false = $cacheService->get($this->safe."ping_false")?$cacheService->get($this->safe."ping_false"):0;
		if(count($ping)<>count($lst_ping)){
			$cacheService->set($this->safe."ping_false",1, 1);
		}else{
			$cacheService->set($this->safe."ping_false",$ping_false+1, 1);
		}
		$cacheService->set($this->safe."ping", count($ping), 1);
		
		if($cacheService->get($this->safe."ping_false")>=3){
			$data["status"]=false;
			// $data["ping"]="连续3次没有鼠标数据";
		}else{
			$data["status"]=true;
			// $data["ping"]=$ping;
		}
		
		$this->ajaxReturn($data);
	}
	public function getgg(){
		$tp = I("get.tp");
		$sid = I("get.sid");
		switch($tp){
			case "gg" : $field = "`notice`";break;
			case "gz" : $field = "`notice_rule`";break;
			case "dj" : $field = "`notice_receive`";break;
		}
		if($field){
			$CFG = M("ShopCfg");
			$data["msg"] = $CFG->where("`sid`=".$sid)->getField($field);
		}else{
			$data["msg"]="没有公告";
		}
		$this->ajaxReturn($data);	
	}
	public function index(){
		$CFG = M("ShopCfg");
		$cfg = current($CFG->where("`sid`=".$this->sid)->getField("id,id,none_anim,taobao_user_id,curtool,lotts,wins,range_time,end_time,order_payment,order_success_times,order_pay_times,front_pic,front_pic_url,front_cfg,deadline,brandid,orderset,cart_items,tms_cartadd,cart_items_pics"));
		if(!$cfg){
			$cfgok=false;
			$Chk = D("Shopadmin/CheckTools");
			$Chk->UserNick = I("get.seller_nick");
			$Chk->IsvCode = C("SM_CODE");
			$Chk->CheckISV(); ;
			if(strtotime($Chk->deadline)<time()){
				$cfg["range_time"]=1;
				$cfg["curtool"]="eggs";
				$errmsg = "您订购的时间已到期，请续费！<br />如果已续费，请发布后刷新，本提示即会消失。";
			}else{
				$cfg["range_time"]=1;
				$cfg["curtool"]="eggs";
				$errmsg = "您尚未配置活动内容，请先登录后台配置活动！";
				// print_r($Chk);
			}
		}else{
			if(strtotime($cfg["deadline"])<time()){
				$Chk = D("Shopadmin/CheckTools");
				$Chk->UserNick = I("get.seller_nick");
				$Chk->IsvCode = C("SM_CODE");
				$Chk->CheckISV();
				if(strtotime($Chk->deadline)<time()){
					$cfgok=false;
					$cfg["range_time"]=1;
					$cfg["curtool"]="eggs";
					$errmsg = "您订购的时间已到期，请续费！<br />如果已续费，请发布后刷新，本提示即会消失。";
				}else{
					$cfgok=true;
					$data["deadline"]=$Chk->deadline;
					$CFG->where("`sid`=".$this->sid)->save($data);
				}
			}else{
				$cfgok=true;
				if(!$cfg["curtool"]){
					$cfg["range_time"]=1;
					$cfg["curtool"]="eggs";
					$errmsg = "您尚未选择活动类型，请点击“编辑”配置活动！";
				}
			}
		}
		
		
		$RANG = D("RangeTime");
		switch($cfg["range_time"]){
			case 1:$RANG->range10();break;
			case 2:$RANG->range20();break;
			case 3:$RANG->range30();break;
			case 4:$RANG->range1h();break;
			case 5:$RANG->range2h();break;
		}
		$E = M("EventsGifts");
		$tools = C("GFT_TYPE");
		$gifts = $E->where("`sid`=".$this->sid." AND `status`<>9")->order("level")->getField("id,level,name,pic_url,type,probability");
		foreach($gifts as $k=>$gift){
			$gifts[$k]["probability"]=$gifts[$k]["probability"]/100;
			switch($gifts[$k]["level"]){
				case 1:
				$gifts[$k]["level"]="一等奖";break;
				case 2:
				$gifts[$k]["level"]="二等奖";break;
				case 3:
				$gifts[$k]["level"]="三等奖";break;
				case 4:
				$gifts[$k]["level"]="鼓励奖";break;
				default:
				$gifts[$k]["level"]="";break;
			}
			foreach($tools as $tool){
				if($gifts[$k]["type"]==$tool["id"]){
					$gifts[$k]["type"]=$tool["name"];
				}
			}
		}
		$G = D("Shopadmin/UsersGifts");
		$G->sid=$this->sid;
		$G->where="sm_events_gifts.type<>7";
		$G->limit="10";
		$G->isfront=true;
		$winner = $G->SendList();
		foreach($winner as $k=>$v){
			$winner[$k]["usernick"]=msubstr($winner[$k]["usernick"],0,2,"UTF-8","*",3);
		}
		$TOOL = M("Tools");
		$tools = $TOOL->getField("templet_code,tool_type,name");
		$cfg["tool_type"]=$tools[$cfg["curtool"]]["tool_type"];
		$cfg["tool_name"]=$tools[$cfg["curtool"]]["name"];
		if($cfg["tool_type"]==3){
			$countdown = $RANG->countdown;
		}else{
		// if($cfg["tool_type"]==1){
			if(strtotime($cfg["start_time"])>time()){
				$countdown = strtotime($cfg["start_time"])-time();
			}else{
				$countdown = strtotime($cfg["end_time"])-time();
			}
		}
		// if($cfg["order_payment"]||$cfg["order_success_times"]||$cfg["order_pay_times"]){
			// $dingdanchoujiang = true;
		// }
		if($cfg["orderset"]==1){
			$dingdanchoujiang = true;
		}
		$TS = M("ToolsStatus");
		if($cfg["curtool"]=="dices"||$cfg["curtool"]=="wheels"){
			$CHKT = D("Shopadmin/CheckTools");
			$toolid = $CHKT->GetToolID($cfg["curtool"]);
			$re = $TS->where("`sid`=".$this->sid." AND `tool_id`=".$toolid)->getField("cfg");
			if($re){
				$dicescfg = json_decode($re,true);
			}
			if(!$re || $dicescfg["onoff"]==0){
				$dicescfg = json_decode(C("DICES_DEFAULT"),true);
				foreach($dicescfg["giftset"] as $k=>$d){
					foreach($gifts as $j=>$gift){
						if($gifts[$j]["level"]=="一等奖"&&$k==2){
							$dicescfg["giftset"][$k]["gift"]=$j;
						}elseif($gifts[$j]["level"]=="二等奖"&&$k==4){
							$dicescfg["giftset"][$k]["gift"]=$j;
						}elseif($gifts[$j]["level"]=="三等奖"&&$k==10){
							$dicescfg["giftset"][$k]["gift"]=$j;
						}elseif($gifts[$j]["level"]=="鼓励奖"&&$k==8){
							$dicescfg["giftset"][$k]["gift"]=$j;
						}elseif($gifts[$j]["level"]==""&&($k==13||$k==6)){
							$dicescfg["giftset"][$k]["gift"]=$j;
						}
					}
				}
			}
			$i = 0;
			foreach($dicescfg["giftset"] as $k=>$c){
				if($c["forbidden"]==false){
					$i++;
				}else{
					unset($dicescfg["giftset"][$k]);
				}
			}
			$dicescfg["giftset"]=array_merge($dicescfg["giftset"]);//重设数组下标
			$dicescfg["count"]=$i;
		}
		foreach($gifts as $k=>$gift){//删除隐含奖品
			if($gifts[$k]["level"]==6){
				unset($gifts[$k]);
			}
		}
		// $JFCFG = $TS->where("`sid`=".$this->sid." AND `tool_id`=13")->getField("cfg");
		// print_r($tools);
		$front_cfg = json_decode(htmlspecialchars_decode($cfg["front_cfg"]),true);
		$this->assign("dicescfg",$dicescfg);
		$this->assign("front_cfg",$front_cfg);
		$this->assign("ddcj",$dingdanchoujiang);
		$this->assign("errmsg",$errmsg);
		$this->assign("cfgok",$cfgok);
		$this->assign("contdown",$countdown);
		// $this->assign("contdown",0);
		$this->assign("cfg",$cfg);
		$this->assign("ctp",$cfg["curtool"]);
		$this->assign("ctptpl","./".$cfg["curtool"].".inc.html");
		$this->assign("lotts",$cfg["lotts"]);
		$this->assign("wins",$cfg["wins"]);
		$this->assign("gifts",$gifts);
		$this->assign("winner",$winner);
		$this->display();
	}
	
}